package team.yidong.fenda.controller;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import team.yidong.fenda.service.HospitalService;
import team.yidong.fenda.service.WxOrderService;

import javax.servlet.http.HttpSession;

/**
 * Created by xuanlong on 2017/12/19.
 */
@Controller
public class WxOrderController {
    @Autowired
    WxOrderService wxOrderService;
    @Autowired
    HospitalService hospitalService;

    @RequiresPermissions("wxOrder")
    @RequestMapping("/wxOrder")
    public String wxOrder(HttpSession session, Model model) {
        Integer hospitalId = (Integer) session.getAttribute("loginHospitalId");
        String sysName = (String) session.getAttribute("loginSysUserName");
        model.addAttribute("sysName", sysName);
        if (hospitalId != 1) {
            JsonConfig jsonConfig = new JsonConfig();
            jsonConfig.setExcludes((new String[]{"hospitalPermissionSet", "hospitalImgSet", "hospitalFieldList", "userSet", "masterList"}));
            model.addAttribute("hospitals", JSONArray.fromObject(hospitalService.findHospitalById(hospitalId), jsonConfig));
        } else {
            JSONArray jsonArray = hospitalService.findAll();
            jsonArray.remove(0);
            model.addAttribute("hospitals", jsonArray);
        }
        return "wxOrder";
    }


    @RequestMapping("/findWxOrder")
    @ResponseBody
    public JSONObject findWxOrder(@RequestParam Integer offset, @RequestParam Integer limit, String userName, String hospitalName, String money, String finishDate, String endDate, String status) {
        JSONObject j = wxOrderService.findWxOrder(offset, limit, userName, hospitalName, money, finishDate, endDate, status);
        Double sum = new Double(0);
        JSONArray jsonArray = j.getJSONArray("rows");
        for (int i = 0; i < jsonArray.size(); i++) {
            sum += Double.parseDouble(jsonArray.getJSONObject(i).get("money").toString());
        }
        j.put("sum", new java.text.DecimalFormat("#.00").format(sum / 100));
        return j;
    }


}
